package com.lianzai.mobile.controller;

import com.lianzai.car.domain.CarInfoDO;
import com.lianzai.car.service.CarInfoService;
import com.lianzai.common.annotation.NoLoginAuthRequired;
import com.lianzai.common.config.WxConfig;
import com.lianzai.common.constant.Constant;
import com.lianzai.common.utils.DateUtils;
import com.lianzai.common.utils.Query;
import com.lianzai.common.utils.R;
import com.lianzai.common.utils.WxUtil;
import com.lianzai.common.utils.jackson.Json;
import com.lianzai.mobile.domain.CarPriceRelaDO;
import com.lianzai.mobile.domain.CommunityInfoDO;
import com.lianzai.mobile.domain.PayOrderDto;
import com.lianzai.mobile.domain.UserAccountDO;
import com.lianzai.mobile.service.CarPriceRelaService;
import com.lianzai.mobile.service.WxNotifyService;
import com.lianzai.payment.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by zb on 2018/10/30.
 */
@Slf4j
@Controller
public class PayNotifyController {

    @Autowired
    private WxNotifyService notifyService;

    @Autowired
    private CarInfoService carInfoService;

    @Autowired
    private CarPriceRelaService carPriceRelaService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private Json json;

    @RequestMapping("/mobile/toPay")
    public ModelAndView toPay(Model model, @RequestParam("carId") Long carId, HttpServletRequest request, HttpServletResponse response) {
        Long userId = (Long)request.getSession().getAttribute(Constant.CURR_USER_ID);
        UserAccountDO userAccountDO = notifyService.selectUserEndDate(userId, carId);
        if(userAccountDO == null || userAccountDO.getCarExpireDate()==null){
            model.addAttribute("endTime", DateUtils.format(new Date(), DateUtils.DATE_PATTERN));
        }else {
            model.addAttribute("endTime", DateUtils.format(userAccountDO.getCarExpireDate(), DateUtils.DATE_PATTERN));
        }
        CarInfoDO carInfo = carInfoService.get(carId.intValue());
        model.addAttribute("carNo", carInfo.getCarNo());
        model.addAttribute("communityName", carInfo.getCommunityName());
        model.addAttribute("carId", carInfo.getId());
        CarPriceRelaDO carPriceRela = carPriceRelaService.get(carId);
        model.addAttribute("amt", carPriceRela.getAmt().setScale(4, BigDecimal.ROUND_HALF_DOWN));
        return new ModelAndView("wechat/pay");
    }

    @RequestMapping(value ="/notify/weixinJsapi", method = RequestMethod.POST)
    @ResponseBody
    public R weixinJsapi(@RequestBody String xml)throws Exception{
        log.info("支付回调接口参数 : {}", xml);
        R result = notifyService.weixinJsapi(xml);
        log.info("支付回调响应结果 : {}", json.obj2string(result));
        return result;
    }


    /**
     * 下预订单
     * @param payOrderDto
     * @return
     */
    @RequestMapping(value ="/mobile/orderIndex/placeOrder", method = RequestMethod.POST)
    @ResponseBody
    public R placeOrder(PayOrderDto payOrderDto, HttpServletRequest request)throws Exception{
        Long userId = (Long)request.getSession().getAttribute(Constant.CURR_USER_ID);
        String openId = (String)request.getSession().getAttribute(Constant.CURR_OPEN_ID);
        payOrderDto.setUserId(userId);
        payOrderDto.setOpenId(openId);
        log.info("下预订单 params:{}", json.obj2string(payOrderDto));
        R result = orderInfoService.placeOrder(payOrderDto);
        log.info("下预订单 result:{}", json.obj2string(result));
        return result;
    }

    /**
     * 下预临时车预订单
     * @param payOrderDto
     * @return
     */
    @NoLoginAuthRequired
    @RequestMapping(value ="/mobile/orderIndex/provisionalOrder", method = RequestMethod.POST)
    @ResponseBody
    public R provisionalOrder(PayOrderDto payOrderDto, HttpServletRequest request)throws Exception{
        String openId = (String)request.getSession().getAttribute(Constant.CURR_OPEN_ID);
        payOrderDto.setOpenId(openId);
        log.info("下预订单 params:{}", json.obj2string(payOrderDto));
        R result = orderInfoService.provisionalOrder(payOrderDto);
        log.info("下预订单 result:{}", json.obj2string(result));
        return result;
    }


    @NoLoginAuthRequired
    @RequestMapping(value = "/coreServlet", method = RequestMethod.GET)
    @ResponseBody
    public String coreServletGet(@RequestParam("signature") String signature,
                                 @RequestParam("timestamp") String timestamp,
                                 @RequestParam("nonce") String nonce,
                                 @RequestParam("echostr") String echostr){
        log.info("微信关注回调  signature:{}, timestamp:{}, nonce:{}, echostr:{}", signature, timestamp, nonce, echostr);
        String wxAttToken = wxConfig.getWxAttToken();
        Boolean flages = WxUtil.checkWxPushSignature(wxAttToken, signature, timestamp, nonce);
        return flages ? echostr : "";
    }


    @NoLoginAuthRequired
    @RequestMapping(value = "/notify/coreServlet", method = RequestMethod.POST)
    @ResponseBody
    public String coreServletPost(HttpServletRequest request){
        return notifyService.coreServletPost(request);
    }

}
